package ci.web.codec;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpRequest;

/**
 * 
 * @author zhh
 */
public class RefererHandler extends HostHandler {

    /**
     * 配置-白名单域名
     * @param domainConfig  白名单域名
     * @param alowNull      是否允许空的referer
     * @return
     */
    public static RefererHandler make(String domainConfig, boolean alowNull){
        if(domainConfig==null || domainConfig.trim().isEmpty()){
            return null;
        }
        String[] arr = domainConfig.split("[;,]");
        HashSet<String> set = new HashSet<String>();
        for(String n:arr){
            n = formatHost(n.trim());
            if(n.length()>0){
                set.add(n);
            }
        }
        arr = set.toArray(new String[set.size()]);
        if(arr.length==0){
            return null;
        }
        if(arr.length==1){
            if(arr[0].equals("*")){
                return null;
            }
            return new RefererHandler(arr[0], alowNull);
        }
        return new RefererHandler(arr, alowNull);
    }
    
    
    
    
    protected boolean alowNull;
    /**
     * 
     * @param host      白名单域名
     * @param alowNull  是否允许空的referer
     */
    protected RefererHandler(String host, boolean alowNull) {
        super(host);
    }
    /**
     * 
     * @param hosts     白名单域名
     * @param alowNull  是否允许空的referer
     */
    protected RefererHandler(String[] hosts, boolean alowNull) {
        super(hosts);
    }

    @Override
    protected boolean checkAlow(final ChannelHandlerContext ctx, final HttpRequest request) {
        String target = request.headers().getAsString(HttpHeaderNames.REFERER);
        boolean ret = false;
        if(target==null||target.length()==0||target.equals("null")){
            ret = alowNull;
        }else{
            try {
                URL u = new URL(target);
                target = u.getHost();
                if(host!=null){
                    ret = equalsHost(host, target, AlowSameRootDomain);
                }else{
                    for(String node : hosts){
                        if(equalsHost(node, target, AlowSameRootDomain)){
                            ret = true;
                            break;
                        }
                    }
                }
            } catch (MalformedURLException e) {
                ret = false;
            }
        }
        if(ret==false){
            forbidden(ctx, target, request);
        }
        return ret;
    }

}
